<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html" ; charset="utf-8" />
    <title>宏宇教育信息采集</title>
    <link href="./index.css" rel="stylesheet" type="text/css" />
  </head>

  <style>
    /* .id-front .el-upload--picture-card, .id-back .el-upload--picture-card, .cun1 .el-upload--picture-card, .cun2 .el-upload--picture-card, .cun1 .el-upload--picture-card, .cun1 .el-upload--picture-card {
        display: none;
    } */
    .hide .el-upload--picture-card {
      display: none;
    }
    .box-card {
      margin: 20px 0;
    }
    
  </style>

  <body>
    <div id="app">
      <app-base-information
        :file-map="fileList"
        type="supplement"
        ref="baseInfo"
        @on-get-info="getInfoByIdNoHandler"
      ></app-base-information>
      <app-education-level
      ref="educationLevel1"
      :file-map="fileList"
      :levelnum="1"
      :level-list="levelList"
      ></app-education-level>
      <app-education-level
        ref="educationLevel2"
        :file-map="fileList"
        :levelnum="2"
        :level-list="levelList"
      ></app-education-level>
      <app-certificate
        :file-map="fileList"
        ref="certificate"
      ></app-certificate>
      <el-row>
        <el-col style="display: flex; justify-content: center">
          <el-button :disabled="isSubmit" @click="handleValid('save')" type="primary">保存</el-button>
        </el-col>
      </el-row>
    </div>

    <script src="../../../js/jquery.js"></script>
    <script src="../../../js/common.js"></script>
    <script src="../../../js/vue.js"></script>
    <script src="../../../js/element.js"></script>
    <script src="./components/BaseInformation.js"></script>
    <script src="./components/EducationLevel.js"></script>
    <script src="./components/Certificate.js"></script>

    <script>
      const app = new Vue({
        el: "#app",
        created() {
          this.infoName = getQuery('trainType');
        },
        mounted() {
          this.getPageTitle();
          this.getEducationOption();
          // 如果是通过操作进入当前页面，就调用获取的接口

          // (this.type = getQuery("type")) && 
          this.getStudentInfo();
        },
        data: {
          isSubmit: false,
          levelList: [],
          // 当前页面的名称
          infoName: '',
          id: "",
          genId: "",
          // type: "",
          oldData: {},
          action: "",
          idNo: "",
          studyId: "",
          baseInfoMap: new Map([
            ["name", "name"],
            ["phoneNum", "phone"],
            ["idNo", "idNum"],
            ["nation", "nationality"],
            ["sex", "gender"],
            ["birthday", "birthday"],
            ["address", "address"],
            ["email", "email"],
            ["qqNumber", "qq"],
            ["workAdress", "work"],
          ]),
          educationLevel: new Map([
            ["major", "discipline"],
            ["educationName", "level"],
            ["studyMode", "path"],
            ["graduateSchool", "school"],
            ["graduateTime", "time"],
            ["certificateNumber", "cerNum"],
          ]),
          fileList: [],
        },
        computed: {},
        methods: {
          // 根据身份证号获取数据并填写
          getInfoByIdNoHandler(data) {
            console.log(`data>>>>>>`, data);
            this.fileList = data.studentCards;

            const {
              educationLevel1: educationLevelInfo,
              educationLevel2: educationLevelInfo2,
            } = this.getRefs("formData");

            for (item of this.educationLevel) {
                  educationLevelInfo[item[1]] = data.student[item[0]];
                  educationLevelInfo2[item[1]] = data.student[item[0] + "2"];
            }
          },
          getPageTitle() {
            // 根据查询字符串info，来判断显示哪个报考信息
            localStorage.setItem('name', '学生管理/学生资料补录')
          },
          handleValid(flag) {
            this.action = flag;
            const errMap = {
              baseInfo: '基本信息未填写完成',
              educationLevel1: '第一学历未填写完成',
              educationLevel2: '第二学历未填写完成',
              certificate: '证书未填写完成',
            };
            const formRef = this.getRefs("$refs");
            Object.keys(formRef).forEach(key => {
              if (formRef[key] === undefined) {
                delete formRef[key]
              }
            });
            const formPList = Object.keys(formRef).map(item => {
              return new Promise((resolve, reject) => {
                formRef[item] && formRef[item].form.validate((valid) => {
                  if (valid) {
                    resolve();
                  } else {
                    reject(errMap[item]);
                  }
                });
              });
            });

            Promise.all(formPList).then(item => {
              this.handleSave();
            }).catch(error => {
              this.$message({
                message: error,
                type: "error",
              });
            })
          },
          getRefs(key = "") {
            const {
              baseInfo = {},
              educationLevel1 = {},
              educationLevel2 = {},
              certificate = {},
            } = this.$refs;

            return {
              baseInfo: baseInfo[key],
              educationLevel1: educationLevel1[key],
              educationLevel2: educationLevel2[key],
              certificate: certificate[key],
            };
          },
          handleSave() {
            const {
              baseInfo,
              educationLevel1,
              educationLevel2,
            } = this.getRefs("formData");

            const { studentEducation = null, studentOccupation = null, studentTitle = null, studentTrain = null } = this.oldData;
            let bkData = {};
            if (studentEducation) {
              delete studentEducation.createDate
              this.genId = studentEducation.id;
              bkData = {studentEducation}
            } else if (studentOccupation) {
              delete studentOccupation.createDate
              this.genId = studentOccupation.id;
              bkData = {studentOccupation}
            } else if (studentTitle) {
              delete studentTitle.createDate
              this.genId = studentTitle.id;
              bkData = {studentTitle}
            } else {
              delete studentTrain.createDate
              this.genId = studentTrain.id;
              bkData = {studentTrain}
            }

            const student = {
              pid: JSON.parse(localStorage.getItem("userInfo")).account.split(
                "-"
              )[1],
              id: this.id,
              // commitFlag: flag === "save" ? 0 : 1,
              name: baseInfo.name,
              phoneNum: baseInfo.phone,
              idNo: baseInfo.idNum,
              nation: baseInfo.nationality,
              sex: baseInfo.gender,
              birthday: baseInfo.birthday,
              address: baseInfo.address,
              email: baseInfo.email,
              qqNumber: baseInfo.qq,
              workAdress: baseInfo.work,
              // 学历1
              major: educationLevel1.discipline,
              educationName: educationLevel1.level,
              studyMode: educationLevel1.path,
              graduateSchool: educationLevel1.school,
              graduateTime: educationLevel1.time,
              certificateNumber: educationLevel1.cerNum,
              // 学历2
              major2: educationLevel2.discipline,
              educationName2: educationLevel2.level,
              studyMode2: educationLevel2.path,
              graduateSchool2: educationLevel2.school,
              graduateTime2: educationLevel2.time,
              certificateNumber2: educationLevel2.cerNum,
            };

            const data = {
              student: [student],
              ...bkData,
            };
            this.save(data);
          },
          save(data) {
            $.ajax({
              url: baseUrl + "studentInfo/updateStudentInfo",
              method: "Post",
              contentType: "application/json;charset=UTF-8",
              data: JSON.stringify({
                ...data,
              }),
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                this.isSubmit = true;
                this.$message({
                  message: `${this.action === 'save' ? '保存成功' : '提交成功'}`,
                  type: "success",
                });
                this.saveFile();
              },
              error: (err, res, res1) => {
                this.$message({
                    message: err.responseJSON.message || "网络错误",
                    type: "error",
                  });
              },
            });
          },
          saveFile() {
            if (!this.id) return;
            const { certificate: certificateFromData } = this.getRefs(
              "formData"
            );
            const {
              baseInfo,
              educationLevel1,
              educationLevel2,
              certificate: certificateFileDic,
            } = this.getRefs("fileDic");
            const formData = new FormData();

            for (item of baseInfo) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of educationLevel1) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of educationLevel2) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of certificateFileDic) {
              formData.append("propertys", certificateFromData[item[0]]);
              formData.append("files", item[1]);
            }
            formData.append("studentId", this.id);
            formData.append("studyId", this.genId);
            formData.append("trainType", this.infoName);
            $.ajax({
              url: baseUrl + "studentInfo/uploadStuCertificate",
              method: "post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              data: formData,
              processData: false,
              contentType: false,
              mimeType: "multipart/form-data",
              success: function (data) {
                window.location.href = '../student/supplement-search.html'
              },
            });
          },
          getStudentInfo() {
            const trainType = getQuery("trainType");
            const idNo = getQuery("idNo");
            const studyId = getQuery("studyId");

            const {
              baseInfo,
              educationLevel1: educationLevelInfo,
              educationLevel2: educationLevelInfo2,
              certificate,
            } = this.getRefs("formData");

            $.ajax({
              url: baseUrl + "studentInfo/getStudentInfo",
              method: "get",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              data: {
                idNo,
                trainType,
                studyId,
              },
              success: (data) => {
                this.oldData = data;
                this.id = data.student.id;
                for (item of this.baseInfoMap) {
                  baseInfo[item[1]] = data.student[item[0]];
                }

                for (item of this.educationLevel) {
                  educationLevelInfo[item[1]] = data.student[item[0]];
                  educationLevelInfo2[item[1]] = data.student[item[0] + "2"];
                }
                this.fileList = data.studentCards;
              },
            });
          },
          getEducationOption() {
            $.ajax({
              url: baseUrl + "education/queryEducationList",
              async: false,
              method: "Post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                this.levelList = data;
                console.log(`this.levelList`, this.levelList);
              },
            });
          },
        },
      });
    </script>
  </body>
</html>
